<template>
    <div>
        <MaskItem :imgPercentage="imgPercentage"></MaskItem>
        <div class="container">
            <div class="crop-demo-btn">选择banner
                <input class="crop-input" type="file" name="image" accept="image/jpg, image/jpeg, image/png, image/gif" @change="uploadTypeImg($event, 1)"/>
            </div>
            <img :src="bannerImg" class="pic-img">
        </div>
        <div class="container" style="margin-top: 20px;">
            <div class="crop-demo-btn">选择课程介绍
                <input class="crop-input" type="file" name="image" accept="image/jpg, image/jpeg, image/png, image/gif" @change="uploadTypeImg($event, 2)"/>
            </div>
            <img :src="courseImg" class="pic-img">
        </div>
        <el-row>
            <el-col :span="24">
                <el-button style="float: right;margin: 10px 0" type="primary" plain size="medium" @click="submit()">保存发布</el-button>
            </el-col>
        </el-row>
    </div>
</template>

<script type="text/ecmascript-6">
    import {baiduCloud} from '@/config/env'
    import {obtainIndexInfo,updateIndexInfo} from '@/config/api'
    import { upLoadFileToOSS } from '@/config/utils'

    import Mask from '../../common/mask.vue'
    export default {
        components: {
            MaskItem: Mask
        },
        data () {
            return {
                // 百度云
                akBos: baiduCloud.akBos,
                skBos: baiduCloud.skBos,
                endpointBos: baiduCloud.endpointBos,
                bucketImgBos: baiduCloud.bucketBos +'/course/image',
                urlImgBos: baiduCloud.urlBos+'/course/image/',
                // 图片上传进度
                imgPercentage: 0,

                // banner图片
                bannerImg:  '',
                // 课程介绍图片
                courseImg: '',
            }
        },
        mounted () {
            // 初始化百度云上传
            this.initBaiDuBce();
            // 获取原始图片
            this.indexInfo();
        },
        methods: {
            // 获取数据
            async indexInfo () {
                let data = await obtainIndexInfo();
                this.bannerImg = data.bannerImg ? data.bannerImg : '';
                this.courseImg = data.courseImg ? data.courseImg : '';
                console.log(data, '获取成功')
            },
            // 提交
            async submit () {
                if (!this.bannerImg) {
                    this.$message({
                        message: '请上传banner图片',
                        type: 'warning'
                    });
                }
                if (!this.courseImg) {
                    this.$message({
                        message: '请上传课介绍图片',
                        type: 'warning'
                    });
                };
                await updateIndexInfo(this.bannerImg,this.courseImg)
                    .then(res => {
                        console.log(res)
                        if ( res.status === 200) {
                            this.$message({
                                message: '发布成功',
                                type: 'success'
                            });
                        } else {
                            this.$message.error('失败');
                        }
                    }).catch(err => {
                        console.error('错误信息',err)
                    });
            },
            // 初始化百度云上传
            initBaiDuBce(){
                let self = this;
                let bosConfig = {
                    credentials: {
                        ak: self.akBos,
                        sk: self.skBos
                    },
                    endpoint: self.endpointBos  // 根据您选用bos服务的区域配置相应的endpoint
                };
                // let bucket = self.bucketBos; // 设置您想要操作的bucket
                self.client = new baidubce.sdk.BosClient(bosConfig);
            },
            // 上传图片
            async uploadTypeImg(event, status){
                let self = this;
                // 课程类型图片状态    0 --- 课程类型banner  1 --- 课程类型证书  2 --- 课程类型介绍
                self.uploadStatus = status;

                // 浏览器兼容 (FF不兼容event.srcElement)
                let evt = event.srcElement ? event.srcElement : event.target;
                let file = evt.files[0]; // 获取要上传的文件
                // 用户取消上传
                if(file == undefined){
                    return;
                }
                const url = await upLoadFileToOSS(file, 'course/image')
                if (url) {
                    // banner
                    if (self.uploadStatus === 1  ) {
                        self.bannerImg = url;
                    };
                    // 课程介绍图
                    if (self.uploadStatus === 2 ) {
                        self.courseImg = url;
                    };
                }
                return false;
                // 生成6位随机数
                let chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
                let res = "";
                for(let i = 0; i < 6 ; i ++) {
                    let id = Math.ceil(Math.random()*61);
                    res += chars[id];
                }
                let key = res + '.' +file.name.split(/\./g).pop(); // 保存到bos时的key，您可更改，默认以文件名作为key
                let blob = file;
                let ext = key.split(/\./g).pop();
                let mimeType = baidubce.sdk.MimeType.guess(ext);
                if (/^text\//.test(mimeType)) {
                    mimeType += '; charset=UTF-8';
                }
                let options = {
                    'Content-Type': mimeType
                };
                self.client.putObjectFromBlob(self.bucketImgBos, key, blob, options)
                    .then(function (res) {
                        // 上传完成，添加您的代码
                        console.log(key,res,'上传成功');
                        // banner
                        if (self.uploadStatus === 1  ) {
                            self.bannerImg = self.urlImgBos + key;
                        };
                        // 课程介绍图
                        if (self.uploadStatus === 2 ) {
                            self.courseImg = self.urlImgBos + key;
                        };
                        console.log('图片上传成功:',self.urlImgBos + key)
                    })
                    .catch(function (err) {
                        // 上传失败，添加您的代码
                        console.log(err);
                    });

                self.client.on('progress', function (evt){
                    // console.log(evt, ".....")
                    // 监听上传进度
                    if (evt.lengthComputable){
                        self.imgPercentage = parseInt((evt.loaded / evt.total) * 100)+'';
                        console.log(self.imgPercentage, "上传图片")
                        self.imgPercentage = String(self.imgPercentage)
                        // 满了，清空进度条
                        if(self.imgPercentage == 100){
                            self.imgPercentage = 0
                        }
                    }
                });
            },

        }
    }
</script>

<style lang="less" scoped>
    .label-bannaer {
        display: inline-block;
    }
    #bannaer {
        opacity: 0;
        display: block;
        width: 100%;
        height: 100%;
    }
    .crop-demo-btn{
        position: relative;
        width: 150px;
        height: 40px;
        line-height: 40px;
        padding: 0 20px;
        background-color: #409eff;
        color: #fff;
        font-size: 14px;
        border-radius: 4px;
        box-sizing: border-box;
        text-align: center;
    }
    .crop-input{
        position: absolute;
        width: 150px;
        height: 40px;
        left: 0;
        top: 0;
        opacity: 0;
        cursor: pointer;
    }
    .pic-img {
        width: 50%;
        margin-top: 25px;
    }
</style>
